<?php

namespace App\Http\Controllers;

use App\Models\Address;
use App\Traits\ValidationTrait;
use Exception;
use Illuminate\Http\Request;

/**
 * 收货地址相关
 */
class AddressController extends Controller
{
    use ValidationTrait;

    /**
     * 我的收货地址
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function delivery_address(Request $request)
    {
        try {
            $status = 0;
            $data   = [];
            $userID = $request->get('user_id');
            if (empty($userID)) {
                throw new Exception('缺少参数！');
            }
            $address = Address::where(['user_id' => $userID, 'is_delete' => 0])->get();
            //处理数据
            foreach ($address as $key => $value) {
                $data[$key]['address_id'] = $value->address_id;
                $data[$key]['name']       = $value->name;
                $data[$key]['phone']      = $value->phone;
                $data[$key]['is_default'] = $value->is_default;
                $data[$key]['address']    = $value->address_name . $value->details;
            }
            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 添加一个收货地址
     * @param Request $request [description]
     */
    public function add_delivery_address(Request $request)
    {
        try {
            $status = 0;
            //验证
            $validator = $this->verify($request, 'validation.add_delivery_address');
            if ($validator->fails()) {
                $messages = $validator->messages()->first();

                throw new Exception($messages);
            }

            $user_id      = $request->get('user_id');
            $name         = $request->get('name');
            $phone        = $request->get('phone');
            $details      = $request->get('details');
            $address_name = $request->get('address_name');
            $zip_code     = $request->get('zip_code');
            $is_default   = $request->get('is_default');
            //设为默认地址
            if ($is_default == 1) {
                Address::where(['user_id' => $user_id, 'is_delete' => 0])->update(['is_default' => 2]);
            }
            Address::create([
                'user_id'     => $user_id,
                'name'        => $name,
                'phone'       => $phone,
                'details'     => $details,
                'is_default'  => $is_default,
                'is_delete'   => 0,
                'create_time' => time(),
                'zip_code'    => $zip_code,
            ]);

            $status = 1;
            $msg    = '操作成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg]);
    }
}
